<?php
namespace app\service;

use app\model\{ChatSession, ChatMessage, User};
use Exception;

class ChatService
{
    /**
     * 获取用户会话列表
     */
    public function getUserSessions(User $user, ?string $type = null, int $page = 1, int $pageSize = 10)
    {
        $query = ChatSession::where('user_id', $user->id);
        
        if ($type) {
            $query->where('session_type', $type);
        }

        return $query->with(['project', 'reminder'])
            ->order('last_message_at', 'desc')
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $page
            ]);
    }

    /**
     * 创建新会话
     */
    public function createSession(User $user, array $data): ChatSession
    {
        $session = new ChatSession;
        $session->user_id = $user->id;
        $session->session_type = $data['session_type'] ?? ChatSession::TYPE_NORMAL;
        $session->project_id = $data['project_id'] ?? null;
        $session->reminder_id = $data['reminder_id'] ?? null;
        $session->learning_records_id = $data['learning_records_id'] ?? null;
        $session->title = $data['title'] ?? '新的会话';
        $session->started_at = time();
        $session->last_message_at = time();
        $session->save();
        
        return $session;
    }

    /**
     * 获取会话消息
     */
    public function getSessionMessages(int $sessionId, User $user, int $page = 1, int $pageSize = 20)
    {
        $session = $this->validateSession($sessionId, $user);

        return ChatMessage::where('session_id', $sessionId)
            ->order('created_at', 'asc')
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $page
            ]);
    }

    /**
     * 发送消息
     */
    public function sendMessage(int $sessionId, User $user, string $content, int $type = null): ChatMessage
    {
        $session = $this->validateSession($sessionId, $user);

        $message = new ChatMessage;
        $message->session_id = $sessionId;
        $message->user_id = $user->id;
        $message->message_type = $type ?? ChatMessage::TYPE_TEXT;
        $message->content = $content;
        $message->is_ai = false;
        $message->save();

        $session->updateLastMessageTime();

        return $message;
    }

    /**
     * 验证会话权限
     */
    protected function validateSession(int $sessionId, User $user): ChatSession
    {
        $session = ChatSession::where('id', $sessionId)
            ->where('user_id', $user->id)
            ->find();

        if (!$session) {
            throw new Exception('会话不存在或无权限');
        }

        return $session;
    }

    /**
     * 获取会话历史消息
     */
    public function getSessionHistory(int $sessionId, ?int $beforeMessageId = null, int $limit = 100): array
    {
        $query = ChatMessage::where('session_id', $sessionId);
        
        if ($beforeMessageId) {
            $query->where('id', '<', $beforeMessageId);
        }

        return $query->order('id', 'desc')
            ->limit($limit)
            ->select()
            ->reverse()
            ->map(function ($msg) {
                return [
                    'role' => $msg->is_ai ? 'assistant' : 'user',
                    'content' => $msg->content,
                    'message_id' => $msg->id
                ];
            })
            ->toArray();
    }
} 